"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 功能测试
Case Name   : CTE+MATERIALIZED（物化）用法测试
Create At   : 2023/7/29
Owner       : n@ningyali
Description :
    1、建表插入数据
    2、CTE+materialized用法测试
    3、CTE+not materialized用法测试
    4、CTE+不指定[not]materialized用法测试
    5、清理环境
Expect      :
    1、成功
    2、成功（外面条件不能内推）
    3、成功，cost小于物化(允许外面条件推进去)
    4、成功，只有一个物化了
    5、成功
History     :
"""

import os
import re
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class CteCase0001(unittest.TestCase):
    def setUp(self):
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.log = Logger()
        self.t_name = 't_cte_0005'
        self.cte_name_1 = 'cte_0005_1'
        self.cte_name_2 = 'cte_0005_2'
        text = f'-----{os.path.basename(__file__)} start-----'
        self.log.info(text)

    def test_1(self):
        text = '-----step1:建表插入数据; expect:成功-----'
        self.log.info(text)
        sql = f"drop table if exists {self.t_name};" \
            f"create table {self.t_name}(id int, name text);" \
            f"insert into {self.t_name} values (generate_series (1," \
            f"100000), substring(md5(random()::varchar),2,10));"
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, res, f'执行失败：{text}')
        self.assertIn('INSERT 0 100000', res, f'执行失败：{text}')

        text = '-----step2:CTE+materialized用法测试; expect:成功（外面条件不能内推）-----'
        self.log.info(text)
        sql = f"explain analyse\n" \
            f"with\n" \
            f"{self.cte_name_1} as materialized (" \
            f"select * from {self.t_name})\n" \
            f"select * from {self.cte_name_1} a join {self.cte_name_1} b " \
            f"on a.id>5 and b.id%2=0 " \
            f"where a.id=(select max(id) from {self.cte_name_1});"
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        pattern = f"Nested Loop.*CTE {self.cte_name_1}.*Seq Scan on " \
            f"{self.t_name}.*Aggregate.*CTE Scan on {self.cte_name_1} a" \
            f".*Filter: \\(\\(id > 5\\) AND \\(id = \\$1\\)\\).*CTE Scan " \
            f"on {self.cte_name_1} b.*Filter: \\(\\(id % 2\\) = 0\\)"
        regex_res = re.search(pattern, res, re.M | re.S)
        self.assertIsNotNone(regex_res, f'执行失败：{text}')

        text = '-----step3:CTE+not materialized用法测试; ' \
               'expect:成功，cost小于物化(允许外面条件推进去)-----'
        self.log.info(text)
        sql = f"explain analyse\n" \
            f"with\n" \
            f"{self.cte_name_1} as not materialized (" \
            f"select * from {self.t_name})\n" \
            f"select * from {self.cte_name_1} a join {self.cte_name_1} b " \
            f"on a.id>5 and b.id%2=0 " \
            f"where a.id=(select max(id) from {self.cte_name_1});"
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        pattern = f"Nested Loop.*Aggregate.*Seq Scan on {self.t_name}.*" \
            f"Filter: \\(\\(id % 2\\) = 0\\).*Materialize.*Seq Scan on" \
            f" {self.t_name}.*Filter: \\(\\(id > 5\\) AND \\(id = \\$0\\)\\)"
        regex_res = re.search(pattern, res, re.M | re.S)
        self.assertIsNotNone(regex_res, f'执行失败：{text}')

        text = '-----step4:CTE+不指定[not]materialized用法测试; ' \
               'expect:成功，只有一个物化了-----'
        self.log.info(text)
        sql = f"explain analyse\n" \
            f"with\n" \
            f"{self.cte_name_1} as (select * from {self.t_name}),\n" \
            f"{self.cte_name_2} as (select * from {self.t_name})\n" \
            f"select * from {self.cte_name_1} a join {self.cte_name_2} b " \
            f"on a.id>5 and b.id%2=0 " \
            f"where a.id=(select max(id) from {self.cte_name_1});"
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        pattern = f"Nested Loop.*CTE {self.cte_name_1}.*Seq Scan on" \
            f" {self.t_name}.*Aggregate.*CTE Scan on {self.cte_name_1}.*CTE" \
            f" Scan on {self.cte_name_1} a.*Filter: \\(\\(id > 5\\) AND " \
            f"\\(id = \\$1\\)\\).*Materialize.*Seq Scan on " \
            f"{self.t_name}.*Filter: \\(\\(id % 2\\) = 0\\)"
        regex_res = re.search(pattern, res, re.M | re.S)
        self.assertIsNotNone(regex_res, f'执行失败：{text}')

    def tearDown(self):
        text = '-----step5:清理环境; expect:成功-----'
        self.log.info(text)
        sql = f"drop table if exists {self.t_name};"
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, res, f'执行失败：{text}')
        text = f'-----{os.path.basename(__file__)} end-----'
        self.log.info(text)
